<template>
  <component :is="tag" :class="classes" @mousedown="mouseDown">
    <slot/>
  </component>
</template>

<script>

export default {
  name: 'CMove',
  props: {
    tag: {
      type: String,
      default () {
        return 'div'
      }
    },
    activeClass: {
      type: String,
      default () {
        return ''
      }
    }
  },
  data () {
    return {
      active: false,
      currentPosition: {
        x: 0,
        y: 0
      }
    }
  },
  created () {
    window.addEventListener('mousemove', this.mouseMove)
    window.addEventListener('mouseup', this.mouseUp)
  },
  beforeDestroy () {
    window.removeEventListener('mousemove', this.mouseMove)
    window.removeEventListener('mouseup', this.mouseUp)
  },
  computed: {
    classes () {
      return this.active ? this.activeClass : ''
    }
  },
  methods: {
    mouseMove (e) {
      if (this.active) {
        const mouse = {
          x: e.clientX,
          y: e.clientY
        }
        this.$emit('move', {
          offsetX: mouse.x - this.currentPosition.x,
          offsetY: mouse.y - this.currentPosition.y,
          x: mouse.x,
          y: mouse.y
        })
        this.currentPosition = mouse
      }
    },
    mouseDown (e) {
      this.currentPosition = {
        x: e.clientX,
        y: e.clientY
      }
      this.active = true
      this.$emit('active', true)
      document.body.className += ' no-select-text'
    },
    mouseUp () {
      if (this.active) {
        this.active = false
        this.$emit('active', false)
        document.body.className = (document.body.className || '').replace('no-select-text', '')
      }
    }
  }
}
</script>

<style></style>
